package com.example.orderfood2.viewAllInformation;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.icu.util.Calendar;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.orderfood2.DatabaseManager.DatabaseManager;
import com.example.orderfood2.R;
import com.example.orderfood2.Repository.TeacherRepository;
import com.example.orderfood2.TeacherActivity;
import com.example.orderfood2.entity.Teacher;
import com.example.orderfood2.util.DBUtil;

import java.util.Arrays;
import java.util.Locale;

public class EditTeacherActivity extends AppCompatActivity {
    private TeacherRepository dbUtil;
    private int Id;
    private Button btnSubmit;
    // 声明UI组件
    private EditText etUsername, etPassword, etScience;
    private RadioGroup radioSex;
    private Spinner spinnerTitle;
    private TextView tvDate;
    private String selectedDate;
    private String source; // 成员变量


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        dbUtil= DatabaseManager.getInstance(this).getTeacherRepository();
        super.onCreate(savedInstanceState);
        // 获取来源标识
        source = getIntent().getStringExtra("source");
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_edit_teacher);
        // 初始化数据库
//        dbUtil = new DBUtil(this);
        // 获取传递过来的ID
        Id = getIntent().getIntExtra("id", -1);
        if(Id==-1){
            Toast.makeText(this, "无效的老师ID", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        // 初始化视图,获取各个组件
        initViews();
        // 加载班级数据
        loadClassData();
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateClassInfo();
                Intent intent;
                if ("TeacherActivity".equals(source)) {
                    intent = new Intent(EditTeacherActivity.this, TeacherActivity.class);
                } else {
                    intent = new Intent(EditTeacherActivity.this, ViewAllTeacherInformationActivity.class);
                }
                // 清理返回栈并跳转
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
                finish(); // 关闭当前 EditClassActivity
            }
        });
    }
    private void initViews(){
        etUsername = findViewById(R.id.et_teacher_username);
        etPassword = findViewById(R.id.et_teacher_password);
        etScience = findViewById(R.id.et_teacher_science);
        radioSex = findViewById(R.id.teacher_sex);
        spinnerTitle = findViewById(R.id.spinner_teacher_title);
        tvDate = findViewById(R.id.teacher_date);
        btnSubmit = findViewById(R.id.teacher_submit);
        // 设置日期选择点击监听
        findViewById(R.id.teacher_date_picker).setOnClickListener(v -> showDatePickerDialog());
    }

    private void loadClassData(){
        Teacher teacher=dbUtil.getTeacherById(Id);
        if(teacher!=null){
            etUsername.setText(teacher.getUsername());
            etPassword.setText(teacher.getPassword());
            etScience.setText(teacher.getScience());

//            findViewById(R.id.teacher_female).setSelected(true);
// 设置性别
            if ("女".equals(teacher.getSex())) {
                RadioButton femaleRadioButton = findViewById(R.id.teacher_female);
                femaleRadioButton.setChecked(true);
            } else {
                RadioButton maleRadioButton = findViewById(R.id.teacher_male);
                maleRadioButton.setChecked(true);
            }
// 设置职称
// 从 strings.xml 获取职称数组
            String[] titles = getResources().getStringArray(R.array.teacher_title);
            // 直接通过数组匹配索引
            int position = Arrays.asList(titles).indexOf(teacher.getTitle());
            if (position != -1) {
                spinnerTitle.setSelection(position);
            } else {
                // 处理未找到的情况（如设置默认值）
                spinnerTitle.setSelection(0); // 默认选中第一个
            }
        // 设置日期
        tvDate.setText(teacher.getDate());
        selectedDate = teacher.getDate();

    } else {
        Toast.makeText(this, "老师信息加载失败", Toast.LENGTH_SHORT).show();
        finish();
    }
    }
    private void updateClassInfo(){
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String science = etScience.getText().toString().trim();
        String sex = ((RadioButton)findViewById(radioSex.getCheckedRadioButtonId())).getText().toString();
        String title = spinnerTitle.getSelectedItem().toString();
        if (username.isEmpty() || password.isEmpty() || science.isEmpty() || selectedDate == null) {
            Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
            return;
        }
        Teacher teacher = new Teacher(null,username, password, sex, title, selectedDate, science);
        if (dbUtil.updateTeacher(Id, teacher)) {
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
        }

    }
    private void showDatePickerDialog(){
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                (view, year, month, dayOfMonth) -> {
                    selectedDate = String.format(Locale.getDefault(),
                            "%d-%02d-%02d", year, month + 1, dayOfMonth);
                    tvDate.setText(selectedDate);
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));

        datePickerDialog.show();
    }
}